/*
 * RestExceptionHandler.java
 * Copyright (c) 2014, 2019, Kiri. 
 * All rights reserved.
 */
package com.onesalt.web.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import com.onesalt.service.ServiceException;
import com.onesalt.web.api.response.Response;

/**
 * 统一异常处理
 *
 * @author kiri
 * @date 2015年3月8日
 * @version 1.0
 */
@ControllerAdvice
public class RestExceptionHandler extends ResponseEntityExceptionHandler {

	private static final Logger logger = LoggerFactory.getLogger(RestExceptionHandler.class);

	@ExceptionHandler(RestException.class)
	protected ResponseEntity<Response> handleRestException(RestException ex, WebRequest request) {
		logger.debug("exception = " + ex + ", request = " + request);
		Response resp = new Response(ex.getCode(), ex.getMessage());
		return new ResponseEntity<Response>(resp, HttpStatus.OK);
	}
	
	@ExceptionHandler(ServiceException.class)
	protected ResponseEntity<Response> handleServiceException(ServiceException ex, WebRequest request) {
		return handleRestException(new RestException(ex), request);
	}
}
